package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.helper.AuthResourceHelper;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.MenuResourceType;
import com.rockcent.mall.lib.domain.enumclass.SystemType;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.AuthUserResourceSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by DK on 17/3/10.
 * 职称管理
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class AuthTitleController extends BaseController{
    private final Logger log = LoggerFactory.getLogger(AuthTitleController.class);

    @Autowired
    private AuthTitleRepository authTitleRepository;

    @Autowired
    private AuthTitleResourceRepository authTitleResourceRepository;

    @Autowired
    private AuthResourceRepository authResourceRepository;

    @Autowired
    private UserMallRepository userMallRepository;

    @Autowired
    private UserMerchantRepository userMerchantRepository;

    @Autowired
    private UserAdminRepository userAdminRepository;

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private AuthUserResourceSrv authUserResourceSrv;

    /**
     * @api {get} /v1/auth/title/list 职称 列表
     * @apiGroup AUTH_TITLE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiSuccess {String} name 职称名称
     * @apiSuccess {String=ADMIN("R端"),MALL("M端"),MERCHANT("B端")} systemType 系统类型
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data" [
     *        {
     *            "id" : 12,
     *            "ownerId" : 12,
     *            "name" : "管理员",
     *            "systemType" : "ADMIN",
     *            "resourceIdList" : [1,2,3,4]
     *        },
     *        ......
     *   ]
     * }
     */
    @RequestMapping(value = Routes.AUTH_TITLE_LIST, method = RequestMethod.GET)
    public JsonResult authTitlePage (HttpServletRequest request, AuthTitleDto dto) {
        RestDoing doing = jsonResult -> {
            String systemType = dto.getSystemType();
            if (StringUtils.isBlank(systemType) || !EnumUtils.isValidEnum(SystemType.class, systemType)) {
                jsonResult.remind("系统类型只允许 ADMIN(\"R端\"),MALL(\"M端\"),MERCHANT(\"B端\")",log);
                return;
            }
            List<AuthTitle> authTitleList = authTitleRepository.findBySystemTypeAndIsDelete(SystemType.valueOf(systemType), Whether.NO);
            if (SystemType.MALL == SystemType.valueOf(systemType) || SystemType.MERCHANT == SystemType.valueOf(systemType)) {
                UserInfoDto userInfoDto = userHelper.getSession(request);
                Long ownerId = null;
                if (SystemType.MALL == SystemType.valueOf(systemType)) {
                    ownerId = userInfoDto.mall.getId();
                }

                if (SystemType.MERCHANT == SystemType.valueOf(systemType)) {
                    ownerId = userInfoDto.merchant.getId();
                }

                if (ownerId == null) {
                    jsonResult.remind("用户ID不能为空",log);
                    return;
                }
                authTitleList = authTitleRepository.findByOwnerIdAndSystemTypeAndIsDelete(ownerId, SystemType.valueOf(systemType), Whether.NO);
            }
            jsonResult.data = authTitleList;
        };
        return doing.go(request ,log);
    }

    /**
     * @api {get} /v1/auth/title/info 职称 详情
     * @apiGroup AUTH_TITLE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiParam {long} id <code>必传参数</code> 职称ID
     *
     * @apiSuccess {long} id 职称ID
     * @apiSuccess {long} ownerId 拥有者ID(R端职称时,为空)
     * @apiSuccess {String} name 职称名称
     * @apiSuccess {String=ADMIN("R端"),MALL("M端"),MERCHANT("B端")} systemType 系统类型
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data" [
     *        {
     *            "id" : 12,
     *            "ownerId" : 12,
     *            "name" : "管理员",
     *            "systemType" : "ADMIN",
     *            "resourceIdList" : [1,2,3,4]
     *        }
     *   ]
     * }
     */
    @RequestMapping(value = Routes.AUTH_TITLE_INFO, method = RequestMethod.GET)
    public JsonResult authTitleInfo(HttpServletRequest request, AuthTitleDto dto){
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(AuthTitle.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            AuthTitle authTitle = authTitleRepository.findOne(dto.getId());
            if (authTitle == null) {
                jsonResult.remind(AuthTitle.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            dto.setId(authTitle.getId());
            dto.setName(authTitle.getName());
            List<AuthTitleResource> authTitleResourceList = authTitleResourceRepository.findByTitleId(dto.getId());
            if (authTitleResourceList != null && authTitleResourceList.size() > 0) {
                List<Long> resourceIdList = authTitleResourceList.stream().map(AuthTitleResource::getResourceId).collect(Collectors.toList());
                dto.setResourceIdList(resourceIdList);
            }
            jsonResult.data = dto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /v1/auth/title/save 职称 保存
     * @apiGroup AUTH_TITLE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     * @apiParam {String} name <code>必传参数</code> 职称 名称
     * @apiParam {Long} resourceIdList  菜单ID集合 例如:[1,2,3]
     * @apiParam {String=ADMIN("R端"),MALL("M端"),MERCHANT("B端")} systemType 系统类型
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.AUTH_TITLE_SAVE, method = RequestMethod.POST)
    public JsonResult authTitleSave (HttpServletRequest request, @RequestBody AuthTitleDto dto) {
        RestDoing doing = jsonResult -> {
            String dtoName = dto.getName();
            if (StringUtils.isBlank(dtoName)) {
                jsonResult.remind("名称不能为空",log);
                return;
            }
            String systemType = dto.getSystemType();
            if (StringUtils.isBlank(systemType) || !EnumUtils.isValidEnum(SystemType.class, systemType)) {
                jsonResult.remind("系统类型只允许 ADMIN(\"R端\"),MALL(\"M端\"),MERCHANT(\"B端\")",log);
                return;
            }
            AuthTitle authTitle = new AuthTitle();
            if (SystemType.MALL == SystemType.valueOf(systemType) || SystemType.MERCHANT == SystemType.valueOf(systemType)) {
                UserInfoDto userInfoDto = userHelper.getSession(request);
                Long ownerId = null;
                if (SystemType.MALL == SystemType.valueOf(systemType)) {
                    ownerId = userInfoDto.mall.getId();
                }

                if (SystemType.MERCHANT == SystemType.valueOf(systemType)) {
                    ownerId = userInfoDto.merchant.getId();
                }

                if (ownerId == null) {
                    jsonResult.remind("用户ID不能为空",log);
                    return;
                }
                authTitle.setOwnerId(ownerId);
            }
            authTitle.setSystemType(SystemType.valueOf(systemType));
            authTitle.setName(dtoName);
            authTitle = authTitleRepository.save(authTitle);
            List<Long> resourceIdList = dto.getResourceIdList();
            List<AuthResourceDto> authResourceList = authResourceRepository.findAuthResourceDtoList(resourceIdList,systemType);
            AuthResourceHelper.SINGLETON.validateIsHave(authResourceList);
            if (resourceIdList != null && resourceIdList.size() > 0) {
                for (Long resourceId : resourceIdList) {
                    AuthTitleResource authTitleResource = new AuthTitleResource();
                    AuthResource authResource = authResourceRepository.findOne(resourceId);
                    if (authResource != null && authResource.getParentId() != null) {
                        authTitleResource.setResourceParentId(authResource.getParentId());
                    }
                    Long authTitleId = authTitle.getId();
                    authTitleResource.setTitleId(authTitleId);
                    authTitleResource.setResourceId(resourceId);
                    Long authTitleOwnerId = authTitle.getOwnerId();
                    authTitleResource.setOwnerId(authTitleOwnerId);
                    SystemType authTitleSystemType = authTitle.getSystemType();
                    authTitleResource.setSystemType(authTitleSystemType);
                    authTitleResourceRepository.save(authTitleResource);
                }
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/auth/title/update 职称 更新
     * @apiGroup AUTH_TITLE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiParam {Long} id <code>必传参数</code> 职称ID
     * @apiParam {String} name <code>必传参数</code> 职称 名称
     * @apiParam {Long} resourceIdList  菜单ID集合 例如:[1,2,3]
     * @apiParam {String=ADMIN("R端"),MALL("M端"),MERCHANT("B端")} systemType 系统类型

     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1"
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.AUTH_TITLE_UPDATE, method = RequestMethod.PUT)
    public JsonResult authTitleUpdate (HttpServletRequest request, @RequestBody AuthTitleDto dto) {
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(AuthTitle.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            String systemType = dto.getSystemType();
            if (StringUtils.isBlank(systemType) || !EnumUtils.isValidEnum(SystemType.class, systemType)) {
                jsonResult.remind("系统类型只允许 ADMIN(\"R端\"),MALL(\"M端\"),MERCHANT(\"B端\")",log);
                return;
            }
            AuthTitle authTitle = authTitleRepository.findByIdAndIsDelete(dto.getId(), Whether.NO);
            if (authTitle == null) {
                jsonResult.remind(AuthTitle.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            if (SystemType.MALL == SystemType.valueOf(systemType) || SystemType.MERCHANT == SystemType.valueOf(systemType)) {
                UserInfoDto userInfoDto = userHelper.getSession(request);
                Long ownerId = null;
                if (SystemType.MALL == SystemType.valueOf(systemType)) {
                    ownerId = userInfoDto.mall.getId();
                    if(authTitle.getOwnerId()==null || ownerId==null || authTitle.getOwnerId().longValue()!=ownerId.longValue()) {
                        jsonResult.remind("ownerId不能为空或数据异常",log);
                        return;
                    }
                }

                if (SystemType.MERCHANT == SystemType.valueOf(systemType)) {
                    ownerId = userInfoDto.merchant.getId();
                    if(authTitle.getOwnerId()==null || ownerId==null || authTitle.getOwnerId().longValue()!=ownerId.longValue()) {
                        jsonResult.remind("ownerId不能为空或数据异常",log);
                        return;
                    }
                }

                if (ownerId == null) {
                    jsonResult.remind("用户ID不能为空",log);
                    return;
                }
            }
            if (StringUtils.isNotBlank(dto.getName())) {
                authTitle.setName(dto.getName());
            }
            if(systemType!=null && (systemType.equals(SystemType.MALL.toString()) || systemType.equals(SystemType.MERCHANT.toString()))) {
                authUserResourceSrv.deleteAuthUserResourceByTitleId(authTitle.getId(),SystemType.valueOf(systemType));
            } else {
                List<AuthTitleResource> authTitleResourceList = authTitleResourceRepository.findByTitleId(dto.getId());
                for (AuthTitleResource authTitleResource : authTitleResourceList) {
                    authTitleResourceRepository.delete(authTitleResource.getId());
                }
            }
            List<Long> resourceIdList = dto.getResourceIdList();
            List<AuthResourceDto> authResourceList = authResourceRepository.findAuthResourceDtoList(resourceIdList,systemType);
            AuthResourceHelper.SINGLETON.validateIsHave(authResourceList);
            if (resourceIdList != null && resourceIdList.size() > 0) {
                for (Long resourceId : resourceIdList) {
                    AuthTitleResource authTitleResource = new AuthTitleResource();
                    authTitleResource.setResourceId(resourceId);
                    authTitleResource.setTitleId(authTitle.getId());
                    authTitleResource.setOwnerId(authTitle.getOwnerId());
                    authTitleResource.setSystemType(authTitle.getSystemType());
                    AuthResource authResource = authResourceRepository.findOne(resourceId);
                    if (authResource != null && authResource.getParentId() != null) {
                        authTitleResource.setResourceParentId(authResource.getParentId());
                    }
                    authTitleResourceRepository.save(authTitleResource);
                }
            }
            if(systemType!=null && (systemType.equals(SystemType.MERCHANT.toString()) || systemType.equals(SystemType.MALL.toString()))) {
                authUserResourceSrv.updateAuthUserResourceByTitleId(authTitle.getId(), SystemType.valueOf(systemType));
            }
            authTitleRepository.save(authTitle);
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/auth/title/delete 职称  删除
     * @apiGroup AUTH_TITLE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiParam {Long} id <code>必传参数</code> 职称ID
     * @apiParam {String=ADMIN("R端"),MALL("M端"),MERCHANT("B端")} systemType 系统类型
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.AUTH_TITLE_DELETE, method = RequestMethod.PUT)
    public JsonResult authTitleDelete (HttpServletRequest request, @RequestBody AuthTitleDto dto) {
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(AuthTitle.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            String systemType = dto.getSystemType();
            if (StringUtils.isBlank(systemType) || !EnumUtils.isValidEnum(SystemType.class, systemType)) {
                jsonResult.remind("系统类型只允许 ADMIN(\"R端\"),MALL(\"M端\"),MERCHANT(\"B端\")",log);
                return;
            }
            AuthTitle authTitle = authTitleRepository.findByIdAndIsDelete(dto.getId(), Whether.NO);
            if (authTitle == null) {
                jsonResult.remind(AuthTitle.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            //M端删除角色
            if (SystemType.MALL == SystemType.valueOf(systemType)) {
                List<UserMall> userMallList = userMallRepository.findByTitleId(authTitle.getId());
                if (userMallList != null && userMallList.size() > 0) {
                    jsonResult.remind("角色已经被使用, 不能删除",log);
                    return;
                }
            }
            //B端删除角色
            if (SystemType.MERCHANT == SystemType.valueOf(systemType)) {
                List<UserMerchant> userMerchantList = userMerchantRepository.findByTitleId(authTitle.getId());
                if (userMerchantList != null && userMerchantList.size() > 0) {
                    jsonResult.remind("角色已经被使用, 不能删除",log);
                    return;
                }
            }
            //R端删除角色
            if (SystemType.ADMIN == SystemType.valueOf(systemType)) {
                List<UserAdmin> userAdminList = userAdminRepository.findByTitleId(authTitle.getId());
                if (userAdminList != null && userAdminList.size() > 0) {
                    jsonResult.remind("角色已经被使用, 不能删除",log);
                    return;
                }
            }
            if(systemType!=null && (systemType.equals(SystemType.MERCHANT.toString()) || systemType.equals(SystemType.MALL.toString()))) {
                authUserResourceSrv.deleteAuthUserResourceByTitleId(authTitle.getId(),SystemType.valueOf(systemType));
            } else {
                List<AuthTitleResource> authTitleResourceList = authTitleResourceRepository.findByTitleId(dto.getId());
                for (AuthTitleResource authTitleResource : authTitleResourceList){
                    authTitleResourceRepository.delete(authTitleResource.getId());
                }
            }
            authTitleRepository.delete(authTitle);
        };
        return doing.go(request, log);
    }

}
